//  Created by 莫瑞权 on 2022/5/19.
//  Copyright © 2022 Talkfun. All rights reserved.

import UIKit

class TFLive1to1: TF1vnMainViewController, TalkfunSDKLiveDelegate,TFVideoArea1to1Delegate,TFWhiteboardToolsDelegate,TalkfunSDKRtcDelegate,TFSetButtonViewDelegate,TFGalleryViewDelegate,TF1to16VideoAreaDelegate,TFkeyNoteViewDelegate,TFFullViewDelegate,TFMarqueeDelegate {

    //画笔类型
    var drawType:TalkfunDrawType = TalkfunDrawTypeStroke
    //指导图
    let launchScreen = TFLaunchScreen()
    var videoFrequentlyClick:Bool = false
    var audioFrequentlyClick:Bool = false
    var sendClick:Bool = false
    //单体禁言
    var chatDisable:Bool = false
    //刷新sdk,防止画板被覆盖
    var isRefresh:Bool = false
    // 切换视频模式的父类
    let pageModeView = UIView()
    // 主播名字
    var zhuboName:String = ""
    //用户昵称
    var userNickname:String = ""
    //主讲状态 //0是主播是主讲人,1是用户是主讲人
    var zhujiangStatus:NSInteger = 0
    //主讲人xid
    var zhujiangxid:String = ""
    //定时倒计时
    let timerView = TFTimerView()
    //转盘
    let turntableView = TFTurntableView()
    //音视频容器
    let mediaContainerView = TFMediaContainerView()
    //桌面分享容器
    let desktopContainerView = TFDesktopContainerView()
    //双击放大
    var isDoubleTouch:Bool = false
    //TODO: 初始化控制器------------------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        //小班模式
        self.modetype = "5"
        //1v1
        self.smallType = "1"
        
        self.fullView.delegate = self
        self.pageModeView.backgroundColor = self.superView.backgroundColor
        self.pageModeView.frame = self.superView.bounds
        self.superView.addSubview(self.pageModeView)
        
        //TODO: 2.桌面分享
        self.addDesktopView()
        //TODO:3.音频视频容器
        self.addMediaView()
        //TODO:初始化SDK
        self.inittalkfunSDKWithToken(self.access_token)
        //TODO:  UI布局
        self.addOtherView()
    }
    func addDesktopView()
    {
        //TODO:桌面分享容器
        self.desktopContainerView.isUserInteractionEnabled = false
        self.desktopContainerView.backgroundColor = UIColor.clear
        self.desktopContainerView.isHidden = true
        self.superView.addSubview(self.desktopContainerView)

        let  deskAreaWidth = self.getMediaAreawidth()
        self.desktopContainerView.frame = CGRect(x: 0, y: 0, width: self.superView.frame.size.width-deskAreaWidth, height: self.superView.frame.size.height)
    }
    func addMediaView()
    {
        self.superView.addSubview(self.mediaContainerView)
        let mediaAreawidth = self.getMediaAreawidth()
        self.mediaContainerView.frame = CGRect(x: 0, y: 0, width: self.superView.frame.size.width-mediaAreawidth, height: self.superView.frame.size.height)
    }
    //1.添加导航栏
    func addNavigationBarTools()
    {
        //添加点击事件
        self.navigationBar.frame = self.superView.bounds
        self.navigationBar.addTopViewAndBottomView()
        self.navigationBar.setButton.isHidden = true
        self.navigationBar.takeThePodium(false, liveStart: false, modetype: self.modetype, smallType: "1", shipinType: "0")
        self.navigationBar.backgroundColor = UIColor.clear
        self.superView.addSubview(self.navigationBar)
        //TODO:返回
        self.navigationBar.backButtonAddTarget(self, action: #selector(btnClick))
        //TODO:设置
        self.navigationBar.setButtonTools.addTarget(self, action: #selector(setButtonToolsClick), for: .touchUpInside)
        //TODO:全屏
        self.navigationBar.isFullButton.addTarget(self, action: #selector(isFullButtonClicck), for: .touchUpInside)
        self.navigationBar.title.text = ""
        self.navigationBar.time.isHidden = true

        //TODO:刷新
        self.navigationBar.refresh.addTarget(self, action: #selector(refreshUI), for: .touchUpInside)

        //TODO:弹幕
        self.navigationBar.barrage.addTarget(self, action: #selector(barrageClick), for: .touchUpInside)

         //TODO: iphone 聊天列表显示隐藏 事件
        self.navigationBar.chat.addTarget(self, action: #selector(self.cahtButtonClick), for: .touchUpInside)
      
        self.navigationBar.inputFieldButton.addTarget(self, action: #selector(self.inputFieldButtonClick), for: .touchUpInside)
       
        self.navigationBar.frontAndRearCamera.addTarget(self, action: #selector(self.frontAndRearCameraClick), for: .touchUpInside)
        
        self.navigationBar.voteBtn.addTarget(self, action: #selector(self.questionButtonClick), for: .touchUpInside)
       
        //课件下载
        self.navigationBar.courseDownBtn.addTarget(self, action: #selector(self.courseDownBtnClick), for: .touchUpInside)
      
    }
    //投票列表
    func addVotingArea()
    {
        self.votingArea.frame = CGRect(x: self.superView.frame.size.width, y: self.chatArea.frame.origin.y, width: self.chatArea.frame.size.width, height: self.chatArea.frame.size.height)

        self.superView.addSubview(self.votingArea)

        //TODO: 获取投票详情

        self.votingArea.voteBlock = {[weak self] vid in
            guard let `self` = self else { return }
            self.getVoteDetail(vid)

        }

        //TODO: 执行投票事件
        self.votingArea.voteDetail.newVoteBlock = { [weak self] (vid,optionsArray) in
            guard let `self` = self else { return }

            let submit = TFSubmit()
            submit.vid = vid
            submit.option = optionsArray
            self.talkfunSDK.voteSubmit(submit) {[weak self]  (code, error) in
                guard let `self` = self else { return }

                      if (code==0) {
                          self.TF_toast("投票成功")
                          self.votingArea.successfulVote(vid as NSString)
                          self.votingArea.voteDetail.successfulVote()

                        }else{
                        self.TF_toast("投票失败")

                    }

            }
        };

    }
   @objc func refreshUI()

    {
          if(self.talkfunSDK.isRefresh == false){
              //先隐藏音视频
              self.mediaContainerView.playStatus(TalkfunMultiMediaStatusChangeListenerClose, time: 0)

              self.promptTool.loading.isHidden = false

              if (self.talkfunSDK.pageMode == TalkfunPageModeCourse) {

                  self.courseLive.video1to1Arae.videoSessionsArray.removeAllObjects()
                  //刷新之后,画板返回原来的状态
                  if (self.isDoubleTouch) {

                      let drawingW = self.pageModeView.frame.size.width - self.courseLive.video1to1Arae.frame.size.width
                      let drawingH = self.pageModeView.frame.size.height

                      self.courseLive.drawing.frame = CGRect(x: 0, y: 0, width: drawingW, height: drawingH)

                      self.courseLive.video1to1Arae.isHidden = false
                  }
              } else if (self.talkfunSDK.pageMode == TalkfunPageModeKeyNote) {  self.keynoteLive.videoArea.videoSessionsArray.removeAllObjects()
                  self.keynoteLive.keynoteView.videoArr.removeAllObjects()
              } else if (self.talkfunSDK.pageMode == TalkfunPageModeGallery) {
                  self.galleryLive.videoArea.videoSessionsArray.removeAllObjects()
              }
              self.isRefresh = false

              self.talkfunSDK.reload()
          }
    }
    @objc func frontAndRearCameraClick()
    {
        self.talkfunSDK.rtcManager.switchCamera()
    }
   // #pragma mark 成为第一响应者
   @objc func inputFieldButtonClick()
    {
        self.keyboardTool.qskQuestions.isHidden = true
        self.keyboardTool.expressionButton.isHidden = false
        self.keyboardTool.commonLanguage.isHidden = false
        //图标改回来
        self.keyboardTool.expressionButton.isSelected = false
        self.keyboardTool.expressionButton.setImage(UIImage.init(named: "HTLive.bundle/huisebiaoqing"), for: .normal)
        self.keyboardTool.inputField.becomeFirstResponder()

    }
    @objc func cahtButtonClick()
    {
        self.isShowTopViewAndBottomView(false)
        self.isShowVotingArea(false)
        self.showChatArea(true)
        self.navigationBar.chat.clearRedDot()
    }
    @objc func isFullButtonClicck()
    {
        self.courseLive.drawing.doubleTapActionBlock!()
    }
    @objc func barrageClick()
    {
        if (self.navigationBar.barrage.tag==0) {
            self.navigationBar.barrage.tag = 1
            self.navigationBar.barrage.setImage(UIImage.init(named: "HTLive.bundle/barrage1vN"), for: .normal)

        }else{
            self.navigationBar.barrage.tag = 0
            self.navigationBar.barrage.setImage(UIImage.init(named: "HTLive.bundle/barrageOff1vN"), for: .normal)

        }

         if (self.navigationBar.barrage.tag==1) {

            
             }else {
                 self.barrageRender.bulletSwitch = false

               
                }
    }

    //5.各种网络错误
    func addTallkFenPromptTool()
    {
        self.promptTool.iphoneXpacing = self.getSafetyZone()
        self.promptTool.clipsToBounds  = false
        self.promptTool.whiteboardWidth = self.superView.frame.size.width
        let x:CGFloat = self.courseLive.video1to1Arae.frame.width
        self.promptTool.frame = CGRect(x: 0, y: 0, width: self.superView.frame.size.width-x, height: self.superView.frame.size.height)
        self.promptTool.backgroundColor = UIColor.clear
        self.promptTool.isUserInteractionEnabled  = false
        self.superView.addSubview(self.promptTool)
    }

  //  #pragma mark  UI布局
    func addOtherView()
    {
        //TODO:  3.添加互动工具
        self.addInteractToos()
        //TODO:  4.聊天区域
        self.addChatArea()
        //TODO: 5.0投票列表
        self.addVotingArea()
        //TODO:  6网络错误  网络不稳定  网络是4G  网络加载中
        self.addTallkFenPromptTool()
        //TODO: 7.0课件下载
        self.initCoursedownView()

        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+2.0) {
            self.promptTool.loading.isHidden = true
        }

        self.superView.addSubview(self.chatArea)
        //TODO:导航栏
        self.addNavigationBarTools()

   
        
        self.fullView.delegate = self
    }
    //#pragma mark  添加互动工具
    func addInteractToos()
    {
    //TODO:定时器(倒计时)
    self.timerView.isHidden = true
    self.superView.addSubview(self.timerView)

    //TODO:转盘
    self.turntableView.isHidden = true
    self.superView.addSubview(self.turntableView)

        //TODO:跑马灯
    self.marquee.delegate = self;
    self.superView.addSubview(self.marquee)

    self.timerView.frame = CGRect(x: (self.superView.frame.size.width - 120)/2, y: (self.superView.frame.size.height - 120)/2, width: 120, height: 120)

    self.turntableView.frame = CGRect(x: (self.superView.frame.size.width-155-12.5)/2, y: (self.superView.frame.size.height-155-12.5)/2, width: 155+12.5, height: 155+12.5)

    self.marquee.frame = CGRect(x: 0, y: 40, width: self.superView.frame.size.width, height: 32)

      if (self.marquee.frame.size.width != self.marquee.view.frame.size.width) {
          self.marquee.refreshData()
      }

    }
    //更新keyNoteframe
    func updetaKeyfalseteViewFrame(_ isOpen:Bool)
    {
        var drawingY:CGFloat = 0

        if (isOpen) {
            drawingY = self.keynoteLive.videoArea.frame.maxY
        } else {
            drawingY = 0
        }
        let drawingX:CGFloat = 0
        let drawingW:CGFloat = self.keynoteLive.view.frame.size.width

        let drawingH:CGFloat = self.keynoteLive.view.frame.size.height-drawingY

        self.keynoteLive.keynoteView.frame = CGRect(x: drawingX, y: drawingY, width: drawingW, height: drawingH)


    }
    func touchesBeganUI()
    {
        self.isShowOtherArea(false)
        self.isShowSetButtonToolsArea(false)
       if (self.navigationBar.topView.frame.origin.y==0) {

           self.isShowTopViewAndBottomView(false)

       }else{
           self.isShowTopViewAndBottomView(true)

       }
        if (self.talkfunSDK.realDesktop == false && self.talkfunSDK.graffiti && self.mediaContainerView.docType != 4) {
            self.courseLive.drawing.whiteboardTools.isHidden = false
        }
        self.showChatArea(false)
        self.isShowVotingArea(false)

    }
   // #pragma mark  画廊模式
    func addgalleryMode()
    {
        self.galleryLive = TFGalleryModeLive()
        self.galleryLive.view.frame = self.pageModeView.bounds
        self.galleryLive.view.backgroundColor = self.pageModeView.backgroundColor
        self.pageModeView.addSubview(self.galleryLive.view)
        self.galleryLive.addTouchView()
        self.galleryLive.videoArea.delegate = self

        if (self.talkfunSDK.roomInfo.mod_zhuboaction_live.config.cup.enable) {
            self.galleryLive.videoArea.showCup = true
        } else {
            self.galleryLive.videoArea.showCup = false
        }

        self.galleryLive.videoArea.collectionView!.touchesBegan = { [weak self]  in
            guard let `self` = self else { return }
            self.touchesBeganUI()
        };
    }
  //  #pragma mark  主讲模式
    func addkeynoteMode()
    {
        self.keynoteLive = TFKeyNoteModeLive()
        self.keynoteLive.view.frame = self.pageModeView.bounds
        self.keynoteLive.view.backgroundColor = self.pageModeView.backgroundColor
        self.pageModeView.addSubview(self.keynoteLive.view)

        self.keynoteLive.addvideoArea()
        self.keynoteLive.videoArea.pageMode = self.talkfunSDK.pageMode
        self.updetaKeyfalseteViewFrame(false)

        self.keynoteLive.keynoteView.delegate = self
        self.keynoteLive.videoArea.delegate = self

        if (self.talkfunSDK.roomInfo.mod_zhuboaction_live.config.cup.enable) {
            self.keynoteLive.videoArea.showCup = true
        } else {
            self.keynoteLive.videoArea.showCup = false
        }
        self.keynoteLive.keynoteView.touchesBegan = { [weak self]  in
            guard let `self` = self else { return }
            self.touchesBeganUI()
        }
    }
   // #pragma mark  课程模式
    func addCourseMode()
    {
        self.courseLive = TFCourseModeLive()
        self.courseLive.view.frame = self.pageModeView.bounds
        self.courseLive.view.isHidden = false
        self.courseLive.view.backgroundColor = self.pageModeView.backgroundColor
        self.pageModeView.addSubview(self.courseLive.view)
        self.courseLive.addVideoArea1to1()
        self.courseLive.video1to1Arae.delegate = self

        let x:CGFloat = self.courseLive.video1to1Arae.frame.width
        self.promptTool.frame = CGRect(x: 0, y: 0, width: self.superView.frame.size.width-x, height: self.superView.frame.size.height)
        //画板
        self.courseLive.drawing.whiteboardTools.delegate = self
        self.courseLive.drawing.isFullButton.isHidden = true

        let drawingX:CGFloat = 0
        let drawingY:CGFloat = 0
        let drawingW:CGFloat = self.pageModeView.frame.size.width - self.courseLive.video1to1Arae.frame.size.width
        let drawingH:CGFloat = self.pageModeView.frame.size.height

        self.courseLive.drawing.frame = CGRect(x: drawingX, y: drawingY, width: drawingW, height: drawingH)
        if (self.talkfunSDK.roomInfo.mod_zhuboaction_live.config.cup.enable) {
            self.courseLive.video1to1Arae.showCup = true
        } else {
            self.courseLive.video1to1Arae.showCup = false
        }
        //双击
        self.courseLive.drawing.doubleTapActionBlock = { [weak self]  in
            guard let `self` = self else { return }

                if (self.talkfunSDK.liveStatus != TalkfunLiveStatusStart && self.courseLive.drawing.frame.size.width != self.pageModeView.frame.size.width) {
                    return;
                }
            UIView.animate(withDuration: 0.5) {
                self.showChatArea(false)
                self.isShowVotingArea(false)

            if ( self.courseLive.drawing.frame.size.width != self.pageModeView.frame.size.width) {
                self.navigationBar.isFullButton.setImage(UIImage.init(named: "HTLive.bundle/shrink1vN"), for: .normal)

                self.courseLive.drawing.frame = self.superView.bounds
                self.courseLive.drawing.isFullButton.setImage(UIImage.init(named: "HTLive.bundle/ppt_narrow"), for: .normal)

                self.courseLive.video1to1Arae.isHidden = true
                self.isDoubleTouch = true
            }else{
                self.courseLive.drawing.isFullButton.setImage(UIImage.init(named: "HTLive.bundle/ppt_enlarge"), for: .normal)

                self.navigationBar.isFullButton.setImage(UIImage.init(named: "HTLive.bundle/fullScreen1vN"), for: .normal)

                self.courseLive.drawing.frame = CGRect(x: drawingX, y: drawingX, width: drawingW, height: drawingH)
                self.courseLive.video1to1Arae.isHidden = false
                self.isDoubleTouch = false

            }
            }

            };
        //画板点击
        self.courseLive.drawing.whiteboardDidTouchedBlock = { [weak self]  in
            guard let `self` = self else { return }
            self.touchesBeganUI()
        }
        self.talkfunSDK.configurePPTContainerView(self.courseLive.drawing.view)
    }

    //初始化SDK
    func inittalkfunSDKWithToken(_ access_token:String)
    {
        //TODO:初始化SDK-----------------
        let params = TalkfunSDKLiveInitParams()
        params.accessToken = access_token
        params.courseType = TalkfunCourseTypeStatusRTC
        self.talkfunSDK.enterRoom(params)

        self.talkfunSDK.delegate = self
        self.talkfunSDK.rtcManager.delegate = self
        self.talkfunSDK.orientationMode = .fixedLandscape
        self.talkfunSDK.scalingMode = .fill
        //配置桌面分享容器
        self.talkfunSDK.configureDesktopContainerView(self.desktopContainerView)
        //配置桌面音视频容器
        self.talkfunSDK.configureMediaContainerView(self.mediaContainerView.playVIew)
        self.isRefresh = true
    }

  //  #pragma mark  直播间状态
    func onLiveStatus(_ status: TalkfunLiveStatus)
    {
        if (status == TalkfunLiveStatusWait)
        {

                if (self.talkfunSDK.pageMode == TalkfunPageModeCourse) {
                    self.promptTool.backgroundImage.imageView.isHidden = false
                    self.promptTool.backgroundImage.label.isHidden = false

                    self.promptTool.backgroundImage.imageView.image = UIImage.init(named: "HTLive.bundle/livestoped")

                    self.promptTool.backgroundImage.label.text = "直播未开始"

                    self.navigationBar.takeThePodium(false, liveStart: false, modetype: self.modetype, smallType: "1", shipinType: "0")

                } else if (self.talkfunSDK.pageMode == TalkfunPageModeKeyNote) {
                    self.promptTool.backgroundImage.isHidden = true

                    self.navigationBar.takeThePodium(false, liveStart: false, modetype: self.modetype, smallType: "1", shipinType: "1")

                    self.navigationBar.barrage.tag = 0
                    self.navigationBar.time.isHidden = true
                    self.navigationBar.title.text = ""
                    self.keynoteLive.keynoteView.video.isHidden = true
                    self.keynoteLive.keynoteView.noStartImg.isHidden = false
                    self.keynoteLive.keynoteView.nameImg.isHidden = true
                    self.keynoteLive.keynoteView.nameBackgroudView.backgroundColor = UIColor(red: 23/255.0, green: 145/255.0, blue: 251/255.0, alpha: 0.8)

                    self.keynoteLive.videoArea.noUserLianmai.isHidden = true

                    self.keyboardWillHide1()


                    self.keynoteLive.videoArea.isHidden = true
                } else if (self.talkfunSDK.pageMode == TalkfunPageModeGallery) {

                    self.navigationBar.takeThePodium(false, liveStart: false, modetype: self.modetype, smallType: "1", shipinType: "2")

                    self.galleryLive.videoArea.isHidden = true
                    self.galleryLive.noStartView.isHidden = false

                    let myString = self.zhuboName as String
                         let rect: CGSize = myString.size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 11)])

                    self.galleryLive.nameLab.frame = CGRect(x: 5, y: self.galleryLive.noStartView.frame.size.height-20, width: rect.width+10, height: 20)

                    self.galleryLive.nameLab.text = self.zhuboName
                }

                if (self.navigationBar.showChat==false) {
                    self.navigationBar.inputField.isHidden = true
                } else {
                    if (self.chatDisable == false) {
                        if (self.mod_beforeclass_live) {
                            self.navigationBar.inputField.isHidden = false
                        } else {
                            self.navigationBar.inputField.isHidden = true
                        }
                    } else {
                        self.navigationBar.inputField.isHidden = true
                    }

                }



        }
        else  if (status == TalkfunLiveStatusStart) {


            self.navigationBar.title.text = self.talkfunSDK.roomInfo.title

            self.promptTool.backgroundImage.label.isHidden = true
            self.promptTool.backgroundImage.imageView.isHidden = true
            self.navigationBar.isFullButton.setImage(UIImage.init(named: "HTLive.bundle/fullScreen1vN"), for: .normal)

            self.promptTool.loading.isHidden = true

                if (self.talkfunSDK.pageMode == TalkfunPageModeGallery){
                    self.navigationBar.takeThePodium(false, liveStart: true, modetype: self.modetype, smallType: "1", shipinType: "2")

                    self.galleryLive.noStartView.isHidden = true
                    self.galleryLive.videoArea.isHidden = false

                } else if (self.talkfunSDK.pageMode == TalkfunPageModeCourse) {
                    self.courseLive.drawing.view.isHidden = false;
                    self.promptTool.backgroundImage.backgroundColor = UIColor.clear
                    if (self.talkfunSDK.isLoadCourseware == false) {
                        self.courseLive.drawing.defaultDrawing1vN.isHidden = false
                    }
                    self.navigationBar.takeThePodium(false, liveStart: true, modetype: self.modetype, smallType: "1", shipinType: "0")


                } else if (self.talkfunSDK.pageMode == TalkfunPageModeKeyNote) {

                    self.navigationBar.takeThePodium(false, liveStart: true, modetype: self.modetype, smallType: "1", shipinType: "1")
                }


        }else{

                if ( self.courseLive.drawing.frame.size.width == self.pageModeView.frame.size.width) {

                    self.courseLive.drawing.doubleTapActionBlock!()
                }

            self.navigationBar.setButton.isHidden = true
            self.promptTool.backgroundImage.imageView.isHidden = false
            self.promptTool.backgroundImage.label.isHidden = false

            self.promptTool.backgroundImage.imageView.image = UIImage.init(named: "HTLive.bundle/livestoped")

            self.promptTool.backgroundImage.label.text = "直播已结束"

            self.promptTool.loading.isHidden = true

            self.fullView.delegate = self
            self.objectFullViewDidDragged(self.fullView)
            


                if (self.talkfunSDK.pageMode == TalkfunPageModeCourse) {
                    self.navigationBar.takeThePodium(false, liveStart: false, modetype: self.modetype, smallType: "1", shipinType: "0")
                    
                    self.courseLive.drawing.defaultDrawing1vN.isHidden = true
                    self.courseLive.drawing.whiteboardTools.isHidden = true
                    self.courseLive.video1to1Arae.liveStop(self.userNickname, zhubonickname: self.zhuboName)
                    self.talkfunSDK.rtcManager.whiteboard.setLineRgbColor(UIColor(red: 0.99, green: 0.18, blue: 0.02, alpha: 1))
                    
                    self.mediaContainerView.isMediaApplicatea = false
                    self.promptTool.backgroundImage.isHidden = false
                } else if (self.talkfunSDK.pageMode == TalkfunPageModeKeyNote) {
                    self.navigationBar.takeThePodium(false, liveStart: false, modetype: self.modetype, smallType: "1", shipinType: "1")
                   
                    self.keynoteLive.videoArea.liveStop()
                    self.keynoteLive.keynoteView.video.isHidden = true
                    self.keynoteLive.keynoteView.noStartImg.isHidden = false
                    self.keynoteLive.keynoteView.nameImg.isHidden = true
                    self.keynoteLive.keynoteView.nameBackgroudView.backgroundColor = UIColor(red: 23/255.0, green: 145/255.0, blue: 251/255.0, alpha: 0.8)
                    
                   
                    self.keynoteLive.videoArea.noUserLianmai.isHidden = true
                    self.promptTool.backgroundImage.isHidden = true
                    self.keyboardWillHide1()
             
                } else if (self.talkfunSDK.pageMode == TalkfunPageModeGallery) {
                    self.navigationBar.takeThePodium(false, liveStart: false, modetype: self.modetype, smallType: "1", shipinType: "2")
                   
                    self.galleryLive.videoArea.liveStop()
                    self.promptTool.backgroundImage.isHidden = true
                    self.galleryLive.videoArea.isHidden = true
                    self.galleryLive.noStartView.isHidden = false
                   
                    
                    let rect: CGSize = self.zhuboName.size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 11)])
                    
                    
                    self.galleryLive.nameLab.frame = CGRect(x: 5, y: self.galleryLive.noStartView.frame.size.height-20, width: rect.width+10, height: 20)
                    
                   
                    self.galleryLive.nameLab.text = self.zhuboName
                }

                if (self.navigationBar.showChat==false) {
                    self.navigationBar.inputField.isHidden = true
                } else {
                    if (self.chatDisable == false) {
                        if (self.mod_afterclass_live) {
                            self.navigationBar.inputField.isHidden = false
                        } else {
                            self.navigationBar.inputField.isHidden = true
                        }
                    } else {
                        self.navigationBar.inputField.isHidden = true
                    }

                }

        }

    }
   // #pragma mark  被踢出房间
    func onMemberKick() {

        let alert = UIAlertController.init(title: "", message: "你被退出房间了", preferredStyle:.alert)
     
        let otherAction:UIAlertAction = UIAlertAction.init(title: "退出", style: .default) { action in
            self.exit()
        }
        alert.addAction(otherAction)
        if  UIDevice.current.model.hasPrefix("iPad") {
            alert.popoverPresentationController?.sourceView = self.superView
            alert.popoverPresentationController?.sourceRect = CGRect(x: 0, y: 0, width: 1.0, height: 1.0)
        }
        
        self.present(alert, animated: true)
    }
    //#pragma mark true :单体禁言  false:单体解除禁言
    func onChatDisable(_ state: Bool)
    {
        if (state) {
            self.chatDisable = true
            self.TF_toast("你已被禁言")

           self.navigationBar.inputField.isHidden = true
        }else{

            self.chatDisable = false
            self.TF_toast("禁言已解除")
               
            self.chatArea.chatIsDisable(false)
            //直播已结束
            if (self.talkfunSDK.liveStatus == TalkfunLiveStatusStop) {
                if (self.mod_afterclass_live) {
                    self.navigationBar.inputField.isHidden = false
                } else {
                    self.navigationBar.inputField.isHidden = true
                }
            } else if (self.talkfunSDK.liveStatus == TalkfunLiveStatusWait) {
                //直播未开始
                if (self.mod_beforeclass_live) {
                    self.navigationBar.inputField.isHidden = false
                } else {
                    self.navigationBar.inputField.isHidden = true
                }
            } else {
                self.navigationBar.inputField.isHidden = false;
            }
        }

    }
    //#pragma mark 桌面分享开始--结束
    func isRealDesktop(_ isDesktop: Bool) {
        if (isDesktop) {
            self.desktopContainerView.isHidden = false
        }else{
            self.desktopContainerView.isHidden = true
        }

    }
//    #pragma mark  弹幕
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.superView.endEditing(true)
    }
    //TODO:退出控制器
  @objc func btnClick()
  {
      let alert = self.showContent("你确定要退出直播间吗?", Message: "", Cancel: "取消", Sure: "确定")

      alert.resultIndex = { [weak self] () in

          guard let `self` = self else { return }

          if (self.talkfunSDK.rtcManager.applyStatus == .allow) {

              self.talkfunSDK.leaveliveroom(self.access_token) { [weak self]  (code, error) in
                  guard let `self` = self else { return }
                  if (code == 0) {

                      self.exit()

                  }

              }

            } else {
                self.exit()

        }
          alert.removeFromSuperview()

        }

    }

 //   #pragma mark  音视频代理
    /**
     * @param status 播放状态
     * @param time   播放时间
     */
    func multiMediaApplicate(_ status: TalkfunMultiMediaStatusChangeListener, time: Int32) {

     if (self.talkfunSDK.pageMode == TalkfunPageModeCourse) {
         
         self.mediaContainerView.playStatus(status, time: NSInteger(time))
   
        ////关闭
        if (status == TalkfunMultiMediaStatusChangeListenerClose) {
            //是否应用了
            self.mediaContainerView.isMediaApplicatea = false
            if (self.navigationBar.topView.frame.origin.y == 0 && self.talkfunSDK.rtcManager.whiteboard.graffiti ) {
                self.courseLive.drawing.whiteboardTools.isHidden = false
            }
        }else if (status != TalkfunMultiMediaStatusChangeListenerError) {
            //是否应用了
            self.mediaContainerView.isMediaApplicatea = true
        }

        }
    }

    /* 应用
     *@param id 素材id
     * @param docType  5：音频 ，4：视频
     * @param title 素材标题
     * @param duration 视频时长
     */
    
    func multiMediaApplicate(_ ID: String, docType type: Int32, title: String, duration: Int32)
  
    {
    if (self.talkfunSDK.pageMode == TalkfunPageModeCourse) {
        if (type==0) {
            self.courseLive.drawing.isFullButton.isHidden = true
        }
        self.mediaContainerView.docType(Int(type), duration: Int(duration))
     

        if (self.mediaContainerView.docType == 4) {
            self.courseLive.drawing.whiteboardTools.isHidden = true
        }
        self.mediaContainerView.isMediaApplicatea = true
        
        self.updatePlayVIewFrame(false)
     }
    }
  //  #pragma mark 设置用户开关
    func SetUserFunction(_ tag: NSInteger, andSwitch: UISwitch) {

        let isopen = andSwitch.isOn

        if (tag == 0) {
            if(self.videoFrequentlyClick == true){

                self.TF_toast("点击太快啦，稍等一下再试试吧")

                return
            }
            self.videoFrequentlyClick = true
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) {
                self.videoFrequentlyClick = false
            }


            let closeVideoState = TalkfunSettingToolsManager.shared().getVideoStatus(self.talkfunSDK.xid)
             if (closeVideoState) {
                 self.TF_toast("主播关闭了你的摄像头")

                 return
             }

            if (self.talkfunSDK.rtcManager.applyStatus == .allow) {
                self.talkfunSDK.closeVideoBeforeOnPodium = false
                
                self.talkfunSDK.rtcManager.setCameraDeviceStatus(!isopen) {[weak self] (code , error, model) in
                    guard let `self` = self else { return }
                    
                    if (self.talkfunSDK.pageMode == TalkfunPageModeCourse) {
                        self.courseLive.video1to1Arae.updateModel(model)

                    } else if (self.talkfunSDK.pageMode == TalkfunPageModeKeyNote) {
                        self.keynoteLive.videoArea.updateModel(model)
                    } else if (self.talkfunSDK.pageMode == TalkfunPageModeGallery) {
                        self.galleryLive.videoArea.updateModel(model)
                    }
                    self.navigationBar.updateModel(model)
                }

            } else {
                self.talkfunSDK.closeVideoBeforeOnPodium = true
            }

            if (!isopen) {
                self.setButtonView.hiddenBtn(true)
            } else {
                self.setButtonView.hiddenBtn(false)
            }

            andSwitch.isOn = !isopen

            TalkfunSettingToolsManager.shared().setToolsSwitchVideo(!isopen, xid: self.talkfunSDK.xid)

        } else if (tag == 1) {
            andSwitch.isOn = !isopen
            self.setButtonView.upDataLanguage()

            self.talkfunSDK.rtcManager.switchCamera()

            TalkfunSettingToolsManager.shared().setToolsSwitchCamera(!isopen, xid: self.talkfunSDK.xid)


        } else if (tag == 2) {
            self.talkfunSDK.rtcManager.setLocalViewMirror(isopen)
            TalkfunSettingToolsManager.shared().setToolsSwitchMirror(!isopen, xid: self.talkfunSDK.xid)

        } else if (tag == 3) {
            self.talkfunSDK.rtcManager.setBeautyEffectOptions(isopen)

            TalkfunSettingToolsManager.shared().setToolsSwitchBeauty(isopen, xid: self.talkfunSDK.xid)

        } else if (tag == 4) {

            if(self.audioFrequentlyClick == true){
                self.TF_toast("点击太快啦，稍等一下再试试吧")
                return
            }
            self.audioFrequentlyClick = true

            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) {
                self.audioFrequentlyClick = false
            }

            let closeAudioState = TalkfunSettingToolsManager.shared().getAudioStatus(self.talkfunSDK.xid)

             if (closeAudioState) {
                 self.TF_toast("主播关闭了你的麦克风")

                 return;
             }

            if (self.talkfunSDK.rtcManager.applyStatus == .allow) {
                self.talkfunSDK.closeAudioBeforeOnPodium = false


                self.talkfunSDK.rtcManager.setMicroPhoneDeviceStatus(!isopen) {[weak self] (code , error, model) in
                    guard let `self` = self else { return }

                    if (self.talkfunSDK.pageMode == TalkfunPageModeCourse) {
                        self.courseLive.video1to1Arae.updateModel(model)
                    } else if (self.talkfunSDK.pageMode == TalkfunPageModeKeyNote) {
                        self.keynoteLive.videoArea.updateModel(model)
                    } else if (self.talkfunSDK.pageMode == TalkfunPageModeGallery) {
                        self.galleryLive.videoArea.updateModel(model)
                    }


                    self.navigationBar.updateModel(model)
                }


            } else {
                self.talkfunSDK.closeAudioBeforeOnPodium = true
            }
            TalkfunSettingToolsManager.shared().setToolsSwitchAudio(!isopen, xid: self.talkfunSDK.xid)

            andSwitch.isOn = !isopen
        } else if (tag == 5) {
            self.talkfunSDK.rtcManager.muteAllRemoteAudio(!isopen)
            TalkfunSettingToolsManager.shared().setToolsSwitchSpeaker(isopen, xid: self.talkfunSDK.xid)

        } else if (tag == 6) {
            andSwitch.isOn = !isopen
       
            TalkfunSettingToolsManager.shared().setToolsSwitchBarrage(!isopen, xid: self.talkfunSDK.xid)
            if andSwitch.isOn  {
                
            }else
            {
                self.barrageRender.bulletSwitch = false

            }
        }else if (tag == 7) {

            if (andSwitch.isOn == false) {
                  //调用 系统设置配置语言
                TFChangeLanguage.sharedInstance.setLanguage(language: "en")

            } else {
                TFChangeLanguage.sharedInstance.setLanguage(language: "zh-Hans")

            }
            andSwitch.isOn = !andSwitch.isOn

            //sdk 保存
            TalkfunSettingToolsManager.shared().setToolsLanguageChange(andSwitch.isOn, xid: self.talkfunSDK.xid)

            self.updataLanguage(isopen)

        }

    }
   // #pragma mark 中英文切换
    func updataLanguage(_ isyes:Bool)
    {
        self.setButtonView.upDataLanguage()
        self.navigationBar.upDataLanguage()
        self.keyboardTool.layoutSubviews()
        self.chatArea.upDataLanguage()
        self.timerView.upDataLanguage()
        self.chatArea.upDataLanguage()
        self.navigationBar.ondium.upDataLanguage(isyes)
        self.votingArea.voteDetail.upDataLanguage()
        self.votingArea.upDataLanguage()
    }
   // #pragma 代理画板当前页的frame
    func whiteboardPageFrame(_ frame: CGRect) {
   
        self.courseLive.drawing.isFullButton.frame = CGRect(x: frame.origin.x+frame.size.width-5-33, y: frame.origin.y+frame.size.height-5-33, width: 33, height: 33)

        let height = self.mediaContainerView.frame.size.height-frame.origin.y*2;

        if (frame.size.height > self.superView.frame.size.height) {
            self.mediaContainerView.pageFrame = CGRect(x: frame.origin.x, y:  frame.origin.y, width: frame.size.width, height: height)
        } else {
            self.mediaContainerView.pageFrame = frame
        }

        let width = frame.size.width + frame.origin.x * 2
        if (width == self.superView.frame.size.width) {
            self.updatePlayVIewFrame(true)
        } else {
            self.updatePlayVIewFrame(false)
        }
    }
    func updatePlayVIewFrame(_ isfull:Bool)
    {
        if (self.mediaContainerView.pageFrame.size.width>0&&self.mediaContainerView.docType != 0 ) {
               //音频
             if (self.mediaContainerView.docType == 5) {
                 self.mediaContainerView.playVIew.frame =  self.mediaContainerView.pageFrame
                 var  mediaAreawidth:CGFloat = 0.0
                 if (isfull) {
                     mediaAreawidth = 0
                 } else {

                     mediaAreawidth = self.getMediaAreawidth()
                 }
                 self.mediaContainerView.frame = CGRect(x: 0, y: 0, width: self.superView.frame.size.width-mediaAreawidth, height: self.superView.frame.size.height)
     
             }else if (self.mediaContainerView.docType == 4 ) {
              //视频
                 var  mediaAreawidth:CGFloat = 0.0
                 if (isfull) {
                     mediaAreawidth = 0
                 } else {

                     mediaAreawidth = self.getMediaAreawidth()
                 }

                 let width = self.superView.bounds.size.width - mediaAreawidth
                 
                 var playVIewWidth = self.superView.bounds.size.height/(9.0/16.0)
                 if (playVIewWidth>width) {
                     playVIewWidth = width
                 }
                 self.mediaContainerView.frame = CGRect(x: 0, y: 0, width: self.superView.frame.size.width-mediaAreawidth, height: self.superView.frame.size.height)
      
                 self.mediaContainerView.playVIew.frame = CGRect(x: (width - playVIewWidth)/2, y: 0, width: playVIewWidth, height: self.superView.bounds.size.height)
 
             }

        }

    }
    // TFFullViewDelegate  全屏缩小的代理
    func objectFullViewDidDragged(_ vc:TFFullView)

    {
        self.talkfunSDK.scalingMode = .fill
        vc.model.isFull = false

        self.fullView.isHidden = true
        self.fullView.removeFromSuperview()
     
            for i in 0..<vc.model.view.subviews.count {

                let subView = vc.model.view.subviews[i] as UIView
                subView.frame = vc.bounds
            }
        


        if (self.talkfunSDK.pageMode == TalkfunPageModeCourse) {

            self.courseLive.video1to1Arae.isFull = false

            self.courseLive.video1to1Arae.tableView.reloadData()

        } else if (self.talkfunSDK.pageMode == TalkfunPageModeKeyNote) {
            self.keynoteLive.videoArea.isFull = false
            
            if self.keynoteLive.videoArea.collectionView != nil {
                self.keynoteLive.videoArea.collectionView!.reloadData()
            }
            

        } else  if (self.talkfunSDK.pageMode == TalkfunPageModeGallery){
            self.galleryLive.videoArea.isFull = false
            if self.galleryLive.videoArea.collectionView != nil {
                self.galleryLive.videoArea.collectionView!.reloadData()
            }
            
        }
    }
    //单击
    func dealSingleTapCourse(_ vc:TFVideoAreaCell)
    {
        self.talkfunSDK.scalingMode = .fill

        self.courseLive.video1to1Arae.isFull = false
        vc.frame = vc.tempFrame;
        self.courseLive.video1to1Arae.tableView.addSubview(vc)

        self.courseLive.video1to1Arae.tableView.reloadData()
    }
    //双击了--主讲模式
    func objectDidDraggedCourse(_ cell: TFVideoAreaCell) {

        self.double_tap_to_full_screenUI(cell.model!)

    }
    //双击了 -- 画廊模式
    func GalleryobjectDidDragged(_ vc: TF1to16VideoAreaCell) {
        self.double_tap_to_full_screenUI(vc.model!)
    }
    func GallerydealSingleTap(_ vc: TF1to16VideoAreaCell) {
        
    }
    //双击了 -- 课程模式
    func objectDidDragged(_ vc: TF1to16VideoAreaCell) {
        self.double_tap_to_full_screenUI(vc.model!)
    }
    //单击
    func dealSingleTap(_ vc: TF1to16VideoAreaCell) {

    }
   //TFkeyNoteViewDelegate
    func objectKeyNoteDidDragged(_ vc: TFkeyNoteView) {

        if (self.talkfunSDK.liveStatus != TalkfunLiveStatusStart) {
            return;
        }
         if (vc.frame.size.height != self.superView.bounds.size.height) {
             self.talkfunSDK.scalingMode = .aspectFit
             self.keynoteLive.keynoteView.frame = self.superView.bounds
             self.keynoteLive.keynoteView.isfullClick = true
             self.keynoteLive.keynoteView.updateVideoFrame()
             self.keynoteLive.keynoteView.zoomButton.isHidden = false
             self.keynoteLive.keynoteView.nameBackgroudView.isHidden = true
         }else{
             self.talkfunSDK.scalingMode = .fill
             self.updetaKeyfalseteViewFrame(true)
             self.keynoteLive.keynoteView.isfullClick = false
             self.keynoteLive.keynoteView.updateVideoFrame()
             self.keynoteLive.keynoteView.zoomButton.isHidden = true
             self.keynoteLive.keynoteView.nameBackgroudView.isHidden = false
         }

    }

    func exit()
   {
       
       self.UIInterfaceOrientationPortrait()
       
       self.awardView.animationDidStop()
       self.marquee.destroy()

       NotificationCenter.default.removeObserver(self)


       self.promptTool.destroy()
       if self.qa_sendTimer != nil {
           self.qa_sendTimer?.invalidate()
           self.qa_sendTimer = nil
       }
       if self.chat_sendTimer != nil {
           self.chat_sendTimer?.invalidate()
           self.chat_sendTimer = nil
       }
       self.promptTool.removeFromSuperview()
       self.navigationBar.destroy()
       self.launchScreen.removeFromSuperview()
       self.talkfunSDK.destroy()
       self.mediaContainerView.removeObserver()
       
       //返回上一页
       self.TF_dismissUI()

    }
    /**
     * @画板载入课件
     */
    func loadCourseware()
    {
      self.courseLive.drawing.defaultDrawing1vN.isHidden = true;
    }
    /* 定时器开始倒计时
    *@param total 总时长
    * @param duration 剩余的时长倒计
    */

    func timerStartWidthTotal(_ total: Int, duration: Int) {

    self.timerView.isHidden = false
    self.timerView.timerStartWidthTotal(total, duration: duration)

    }
    /*
    // 定时器暂停
    // @param duration 剩余的时长倒计
    */
    func timerPause(_ duration: Int) {
        self.timerView.timerPause(duration)
    }
    /* 结束定时器
     */
    func timerClose() {
        self.timerView.isHidden = true
    }

    /*
     定时器重新开始
    */
    func timerReReady() {
        self.timerView.endTimeLaer()
    }

    /*
      定时器倒计时完成
    */
    func timerEnd() {
        self.timerView.endTimeLaer()
    }
   // #pragma mark  转盘的代理
    //转盘应用
    func turntableApplicate() {
        self.turntableView.turntableApplicate()
    }
    /* 转盘应用
       selected 选中的号码
       frequency 转盘未关闭前共转了多少次
    */
    func turntableSelected(_ selected: Int, frequency count: Int) {
        self.turntableView.startRotationAnimation(CGFloat(selected))
    }
    //转盘关闭
    func turntableClose() {
        self.turntableView.closeButtonClict()
    }
 
    //#pragma mark 切换主讲人
    func onSwitchZhujiang(_ obj: TFKeyNote) {
   
        let xid = obj.xid as String
        let status = obj.status as NSInteger
        self.zhujiangStatus = status

        let model1 = self.keynoteLive.keynoteView.videoArr[0] as! TalkfunRtcModel
   
         if (status == 0) {
             self.zhujiangxid = "1"
             
             for i in 0..<self.keynoteLive.videoArea.videoSessionsArray.count {
           
                 let model = self.keynoteLive.videoArea.videoSessionsArray[i] as! TalkfunRtcModel
                 if (model.role == .roleeUser) {

                 } else {
                     self.keynoteLive.videoArea.videoSessionsArray.replaceObject(at: i, with: model1)
               
                     self.keynoteLive.videoArea.collectionView!.reloadData()
                     self.keynoteLive.keynoteView.videoArr.removeAllObjects()
                     
                     self.keynoteLive.keynoteView.updetaModel(model, lianmai: true)
                 }

               }

            }
           else if (status==1) {
               self.zhujiangxid = xid
               for i in 0..<self.keynoteLive.videoArea.videoSessionsArray.count {
                let model = self.keynoteLive.videoArea.videoSessionsArray[i] as! TalkfunRtcModel

                    if (model.xid  == xid ) {
                        self.keynoteLive.videoArea.videoSessionsArray.replaceObject(at: i, with: model1)
                      
                        self.keynoteLive.videoArea.collectionView!.reloadData()
                        self.keynoteLive.keynoteView.videoArr.removeAllObjects()
                        self.keynoteLive.keynoteView.updetaModel(model, lianmai: true)
                      
                    }
                }

            }
      

    }
   // #pragma mark 切换视频模式
    func onSwitchVideoMode(_ mode: TalkfunPageMode) {
   
        if (mode == TalkfunPageModeCourse) {
            self.talkfunSDK.pageMode = TalkfunPageModeCourse
            self.addCourseMode()
            self.courseLive.video1to1Arae.videoSessionsArray.removeAllObjects()
            self.mediaContainerView.isHidden = false
            if (self.talkfunSDK.liveStatus == TalkfunLiveStatusStop) {
                if (self.courseLive.drawing.frame.size.width == self.pageModeView.frame.size.width) {
                    self.courseLive.drawing.doubleTapActionBlock!()
                  
                }
                self.navigationBar.setButton.isHidden = true
                self.promptTool.backgroundImage.imageView.isHidden = false
                self.promptTool.backgroundImage.label.isHidden = false
               
                self.promptTool.backgroundImage.imageView.image = UIImage.init(named: "HTLive.bundle/livestoped")
                
                self.promptTool.backgroundImage.label.text = "直播已结束"

                self.promptTool.loading.isHidden = true
                self.navigationBar.takeThePodium(false, liveStart: false, modetype: self.modetype, smallType: "1", shipinType: "0")
              

                self.courseLive.drawing.whiteboardTools.isHidden = true
                
                self.courseLive.video1to1Arae.liveStop(self.userNickname, zhubonickname: self.zhuboName)
                self.talkfunSDK.rtcManager.whiteboard.setLineRgbColor(UIColor(red: 0.99, green: 0.18, blue: 0.02, alpha: 1))
                
              
                self.mediaContainerView.isMediaApplicatea = false
                self.promptTool.backgroundImage.isHidden = false
                self.galleryLive.view.removeFromSuperview()
//                self.galleryLive = nil
                self.keynoteLive.view.removeFromSuperview()
//                self.keynoteLive = nil
            } else if (self.talkfunSDK.liveStatus == TalkfunLiveStatusWait) {
                self.promptTool.backgroundImage.imageView.isHidden = false
                self.promptTool.backgroundImage.label.isHidden = false
                self.promptTool.backgroundImage.isHidden = false
                
                self.promptTool.backgroundImage.imageView.image = UIImage.init(named: "HTLive.bundle/livestoped")
                
                self.promptTool.backgroundImage.label.text = "直播未开始"

            } else {
                //获取上讲台的数据源
                if (self.galleryLive.videoArea.videoSessionsArray.count > 0) {
                    
                    self.courseLive.video1to1Arae.videoSessionsArray.addObjects(from: self.galleryLive.videoArea.videoSessionsArray as! [Any])
                    
                    self.galleryLive.view.removeFromSuperview()
//                    self.galleryLive = nil
                } else {
                    self.courseLive.video1to1Arae.videoSessionsArray.addObjects(from: self.keynoteLive.keynoteView.videoArr as! [Any])
                    
                    self.courseLive.video1to1Arae.videoSessionsArray.addObjects(from: self.keynoteLive.videoArea.videoSessionsArray as! [Any])
                    

                    self.keynoteLive.view.removeFromSuperview()
//                    self.keynoteLive = nil
                }

                if (self.drawPower) {
                    self.courseLive.drawing.whiteboardTools.isHidden = false;
                } else {
                    self.courseLive.drawing.whiteboardTools.isHidden = true;
                }
                self.courseLive.videoArea.isHidden = false;

                if (self.talkfunSDK.isLoadCourseware == false) {
                    self.courseLive.drawing.defaultDrawing1vN.isHidden = false;
                }

                self.promptTool.loading.isHidden = true
                for i in 0..<self.courseLive.video1to1Arae.videoSessionsArray.count {
                
                    let model = self.courseLive.video1to1Arae.videoSessionsArray[i] as! TalkfunRtcModel
                    self.courseLive.video1to1Arae.isHidden = false
                    self.courseLive.video1to1Arae.addModel(model)
                   

                }
            }


        } else if (mode == TalkfunPageModeKeyNote) {
            self.talkfunSDK.pageMode = TalkfunPageModeKeyNote
            self.addkeynoteMode()
           
            self.keynoteLive.videoArea.videoSessionsArray.removeAllObjects()
            self.mediaContainerView.isHidden = true
            self.promptTool.loading.isHidden = true
            if (self.talkfunSDK.liveStatus == TalkfunLiveStatusStop) {
                self.navigationBar.takeThePodium(false, liveStart: false, modetype: self.modetype, smallType: "1", shipinType: "1")
               
                self.keynoteLive.videoArea.liveStop()
                self.promptTool.backgroundImage.isHidden = true
                self.keynoteLive.keynoteView.video.isHidden = true
                self.keynoteLive.keynoteView.noStartImg.isHidden = false
                self.keynoteLive.keynoteView.nameImg.isHidden = true
                self.keynoteLive.keynoteView.nameBackgroudView.backgroundColor = UIColor(red: 23/255.0 , green: 145/255.0, blue: 251/255.0, alpha: 0.8)
               
                self.keynoteLive.videoArea.noUserLianmai.isHidden = true
                self.keynoteLive.keynoteView.nameLab.text = self.zhuboName
                self.keynoteLive.keynoteView.updateNameFram(self.zhuboName, backcolor: true)
              
            } else if (self.talkfunSDK.liveStatus == TalkfunLiveStatusWait) {
                self.promptTool.loading.isHidden = true

                self.promptTool.backgroundImage.imageView.isHidden = false
                self.promptTool.backgroundImage.label.isHidden = false
               
                self.promptTool.backgroundImage.imageView.image =  UIImage.init(named: "HTLive.bundle/livestoped")
                self.promptTool.backgroundImage.label.text = "直播未开始"
                self.keynoteLive.videoArea.isHidden = true
            } else if (self.talkfunSDK.liveStatus==TalkfunLiveStatusStart){
                self.keynoteLive.keynoteView.video.isHidden = false
                //获取上讲台的数据源
                if (self.courseLive.video1to1Arae.videoSessionsArray.count > 0) {
                    self.keynoteLive.videoArea.videoSessionsArray.addObjects(from: self.courseLive.video1to1Arae.videoSessionsArray as! [Any])

                    self.courseLive.view.removeFromSuperview()
//                    self.courseLive = nil;
                } else {
                    self.keynoteLive.videoArea.videoSessionsArray.addObjects(from: self.galleryLive.videoArea.videoSessionsArray as! [Any])
                  
                    self.galleryLive.view.removeFromSuperview()
//                    self.galleryLive = nil;
                }

                self.updetaKeyfalseteViewFrame(true)
                
                
                let copyVideoSessionsArray = NSMutableArray.init(array: self.keynoteLive.videoArea.videoSessionsArray)
                
                for i in 0..<copyVideoSessionsArray.count {

                    let model = copyVideoSessionsArray[i] as! TalkfunRtcModel
                    self.keynoteLive.videoArea.isHidden = false

                    self.keynoteLive.videoArea.removeAdminModel(model)
                    self.keynoteLive.keynoteView.updetaModel(model, lianmai: false)
                
                }

            }


        } else if (mode == TalkfunPageModeGallery) {

            self.talkfunSDK.pageMode = TalkfunPageModeGallery
            self.addgalleryMode()
            
            self.galleryLive.videoArea.videoSessionsArray.removeAllObjects()
            self.mediaContainerView.isHidden = true
            //获取上讲台的数据源
            if (self.talkfunSDK.liveStatus == TalkfunLiveStatusStop) {
                self.promptTool.backgroundImage.isHidden = true
                
                self.navigationBar.takeThePodium(false, liveStart: false, modetype: self.modetype, smallType: "1", shipinType: "2")
                
            
                self.navigationBar.barrage.tag = 0
                self.navigationBar.time.isHidden = true
                self.navigationBar.title.text = ""
                self.galleryLive.videoArea.liveStop()
                self.galleryLive.videoArea.isHidden = true
                self.galleryLive.noStartView.isHidden = false

                let rect: CGSize = self.zhuboName.size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 11)])
                
                
                self.galleryLive.nameLab.frame = CGRect(x: 5, y: self.galleryLive.noStartView.frame.size.height-20, width: rect.width+10, height: 20)
                
                self.galleryLive.nameLab.text = self.zhuboName
            } else if (self.talkfunSDK.liveStatus == TalkfunLiveStatusWait) {
                self.promptTool.loading.isHidden = true
                self.promptTool.backgroundImage.isHidden = true
                self.galleryLive.videoArea.isHidden = true
                self.galleryLive.noStartView.isHidden = false
                
                let rect: CGSize = self.zhuboName.size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 11)])
            
                self.galleryLive.nameLab.frame = CGRect(x: 5, y:  self.galleryLive.noStartView.frame.size.height-20, width: rect.width+10, height: 20)
                
               
                self.galleryLive.nameLab.text = self.zhuboName

            } else {
                if (self.courseLive.video1to1Arae.videoSessionsArray.count > 0) {
                    self.galleryLive.videoArea.videoSessionsArray.addObjects(from: self.courseLive.video1to1Arae.videoSessionsArray as! [Any])
                  
                    self.courseLive.view.removeFromSuperview()
//                    self.courseLive = nil;
                } else {
                    self.galleryLive.videoArea.videoSessionsArray.addObjects(from: self.keynoteLive.keynoteView.videoArr as! [Any])
                    
                    self.galleryLive.videoArea.videoSessionsArray.addObjects(from: self.keynoteLive.videoArea.videoSessionsArray as! [Any])
               
                    self.keynoteLive.view.removeFromSuperview()
//                    self.keynoteLive = nil;
                }


                self.galleryLive.videoArea.isHidden = false;
            }

        }

    }
 //   #pragma mark  ------------------RTC 模式TalkfunSDKRtcDelegate-----------------------
   // #pragma mark 允许上讲台
    func rtcUp(_ model: TalkfunRtcModel) {
   
        if(model.isMe){
            self.courseLive.drawing.podiumConfiguration.podiumStatus(TalkfunApplyStatus.allow)
         
            self.navigationBar.updateModel(model)

        }

        if (self.talkfunSDK.pageMode == TalkfunPageModeCourse) {
            self.navigationBar.takeThePodium(true, liveStart: true, modetype: self.modetype, smallType: "1", shipinType: "0")
            
            self.courseLive.video1to1Arae.addModel(model)
        } else if (self.talkfunSDK.pageMode == TalkfunPageModeKeyNote) {
      
            
            self.navigationBar.takeThePodium(true, liveStart: true, modetype: self.modetype, smallType: "1", shipinType: "1")
            
            if (self.zhujiangStatus == 0) {
                if (model.role == .roleeUser) {

                    self.keynoteLive.videoArea.updateModel(model)
                    self.keynoteLive.videoArea.noUserLianmai.isHidden = true
                    self.keynoteLive.videoArea.isHidden = false
                    self.updetaKeyfalseteViewFrame(true)

                } else {

                    self.keynoteLive.videoArea.removeAdminModel(model)
                    self.keynoteLive.keynoteView.updetaModel(model, lianmai: false)
                

                }
            } else {

                if (model.xid == self.zhujiangxid) {
                    self.keynoteLive.videoArea.removeAdminModel(model)
                    self.updetaKeyfalseteViewFrame(true)
                    self.keynoteLive.keynoteView.updetaModel(model, lianmai: false)
                  
                } else {
                    self.keynoteLive.videoArea.updateModel(model)
                    self.keynoteLive.videoArea.noUserLianmai.isHidden = true
                    self.keynoteLive.videoArea.isHidden = false
                    self.updetaKeyfalseteViewFrame(true)
                }
            }
        } else if (self.talkfunSDK.pageMode == TalkfunPageModeGallery) {
            self.navigationBar.takeThePodium(true, liveStart: true, modetype: self.modetype, smallType: "1", shipinType: "2")
           
            self.galleryLive.videoArea.updateModel(model)
        }


    }
   // #pragma mark 踢下讲台
    func rtcKick(_ model: TalkfunRtcModel) {
        self.rtcDown(model)
    }
   // #pragma mark 主动下讲台
    func rtcDown(_ model: TalkfunRtcModel) {
        
        if (model.isMe) {
            self.courseLive.drawing.podiumConfiguration.podiumStatus(TalkfunApplyStatus.noApply)
       
        }

        if (self.talkfunSDK.pageMode == TalkfunPageModeCourse) {
            self.navigationBar.takeThePodium(false, liveStart: true, modetype: self.modetype, smallType: "1", shipinType: "0")
       
            self.courseLive.video1to1Arae.rtcDown(model)
        } else if (self.talkfunSDK.pageMode == TalkfunPageModeKeyNote) {
         
            self.navigationBar.takeThePodium(false, liveStart: true, modetype: self.modetype, smallType: "1", shipinType: "1")
            
            self.keynoteLive.videoArea.removeFromVideo(model)
            self.keynoteLive.videoArea.noUserLianmai.isHidden = false
        } else if (self.talkfunSDK.pageMode == TalkfunPageModeGallery) {
        
            self.navigationBar.takeThePodium(false, liveStart: true, modetype: self.modetype, smallType: "1", shipinType: "2")
            self.galleryLive.videoArea.removeFromVideo(model)
        }
    }
    
    func upPageModel(_ model:TalkfunRtcModel)
    {
        if (self.talkfunSDK.pageMode == TalkfunPageModeCourse) {
            self.courseLive.video1to1Arae.updateModel(model)
        
        } else if (self.talkfunSDK.pageMode == TalkfunPageModeKeyNote) {

            if (model.xid == self.zhujiangxid || model.role == .roleSpadmin) {
                self.keynoteLive.keynoteView.updetaModel(model, lianmai: true)
               
            } else {
                self.keynoteLive.videoArea.update1to1Model(model)
              
            }
        } else if (self.talkfunSDK.pageMode == TalkfunPageModeGallery){
            self.galleryLive.videoArea.updateModel(model)
        }
    }
   // #pragma mark 打开摄像头
    func rtcOpenVideo(_ model: TalkfunRtcModel) {
   
        if (model.isFull) {
            self.fullView.view.isHidden = true
            self.fullView.backgroundColor = UIColor.clear
            self.fullView.insertSubview(model.view, at: 0)
           
        } else {
            self.fullView.view.isHidden = true
        }

    self.upPageModel(model)

    if (model.isMe) {
        self.TF_toast("你可以使用摄像头了")
        TalkfunSettingToolsManager.shared().setZhuboCloseVideoStatus(false, xid: self.talkfunSDK.xid)
       
        self.setButtonView.hiddenBtn(true)

        self.navigationBar.updateModel(model)

    }

    }
    //#pragma mark 关闭摄像头
    func rtcCloseVideo(_ model: TalkfunRtcModel)
    {
        if (model.isFull) {
            self.fullView.view.isHidden = false
            self.fullView.backgroundColor = UIColor.clear
        } else {
            self.fullView.view.isHidden = true
        }
        
        self.upPageModel(model)
        
    if (model.isMe) {
        self.TF_toast("你的摄像头已关闭")
        TalkfunSettingToolsManager.shared().setZhuboCloseVideoStatus(true, xid: self.talkfunSDK.xid)
       
        self.setButtonView.hiddenBtn(false)
        self.navigationBar.updateModel(model)

    }
        
    }
    //#pragma mark 打开麦克风
    func rtcOpenAudio(_ model: TalkfunRtcModel) {
  
        self.upPageModel(model)
        if (model.isMe) {
            self.TF_toast("你的麦克风已开启")
            TalkfunSettingToolsManager.shared().setZhuboCloseAudioStatus(false, xid: self.talkfunSDK.xid)
           
            let switches = self.setButtonView.swicthArr[4] as! TFSwitch
            switches.isOn = true

            self.navigationBar.updateModel(model)

        }

    }
    
  //  #pragma mark 关闭麦克风
    func rtcCloseAudio(_ model: TalkfunRtcModel) {
   
    self.upPageModel(model)

    if (model.isMe) {
        self.TF_toast("你的麦克风已关闭")
        TalkfunSettingToolsManager.shared().setZhuboCloseAudioStatus(true, xid: self.talkfunSDK.xid)
        
        let switches = self.setButtonView.swicthArr[4] as! TFSwitch
        switches.isOn = false

        self.navigationBar.updateModel(model)

    }
        
    }

    //#pragma mark  打开涂鸦权限
    func rtcDrawEnable(_ model: TalkfunRtcModel) {
  
        self.drawPower =  true
        if (self.talkfunSDK.pageMode == TalkfunPageModeCourse) {

            model.drawPower = true

            self.courseLive.video1to1Arae.updateModel(model)

            if (model.isMe) {
                self.courseLive.drawing.whiteboardTools.isHidden = false
            } else {
                if(self.courseLive.drawing.whiteboardTools.isHidden==false){
                    //不是自己就隐藏
                    self.courseLive.drawing.whiteboardTools.isHidden = true
                }
            }

        } else if (self.talkfunSDK.pageMode == TalkfunPageModeKeyNote) {
            if (model.xid  == self.zhujiangxid) {
                self.keynoteLive.keynoteView.updetaModel(model, lianmai: true)
                
                
            } else {
                self.keynoteLive.videoArea.update1to1Model(model)
               
            }
        } else if (self.talkfunSDK.pageMode == TalkfunPageModeGallery){
            self.galleryLive.videoArea.updateModel(model)
        }

        if (model.isMe)
        {
            self.TF_toast("你已被授予涂鸦权限")
      

        }else{
            self.TF_toast("你的涂鸦权限已被收回")
   

        }

    }
    //#pragma mark  关闭涂鸦权限
    func rtcDrawDisable(_ model: TalkfunRtcModel) {
   
        self.drawPower =  false
        if (self.talkfunSDK.pageMode == TalkfunPageModeCourse) {
            self.courseLive.video1to1Arae.updateModel(model)
        } else if (self.talkfunSDK.pageMode == TalkfunPageModeKeyNote) {

            if (model.xid == self.zhujiangxid) {
                self.keynoteLive.keynoteView.updetaModel(model, lianmai: true)
               
            } else {
                self.keynoteLive.videoArea.update1to1Model(model)
                
            }
        } else if (self.talkfunSDK.pageMode == TalkfunPageModeGallery) {
            self.galleryLive.videoArea.updateModel(model)
        }

    if (model.isMe) {
        self.TF_toast("你的涂鸦权限已被收回")
    
         self.courseLive.drawing.whiteboardTools.isHidden = true
      }
        
    }
   // #pragma mark 未连麦人员打开涂鸦权限
    func onMemberDrawEnable(_ model: TFMember) {
    
        self.drawPower = true;
        if (model.isMe) {
            self.TF_toast("你已被授予涂鸦权限")
        
            self.courseLive.drawing.whiteboardTools.isHidden = false
        }
    }
    //#pragma mark 未连麦人员关闭涂鸦权限
    func onMemberDrawDisable(_ model: TFMember)
 
    {
        self.drawPower = false;
        if (model.isMe) {
            self.TF_toast("你的涂鸦权限已被收回")
         
            self.courseLive.drawing.whiteboardTools.isHidden = true
        }
    }
    //#pragma mark  奖励
    func rtcAward(_ model: TalkfunRtcModel) {
   
        if (self.talkfunSDK.pageMode == TalkfunPageModeCourse) {
            self.courseLive.video1to1Arae.updateModel(model)
           
        } else if (self.talkfunSDK.pageMode == TalkfunPageModeKeyNote) {
            
            if (model.xid == self.zhujiangxid) {
                self.keynoteLive.keynoteView.updetaModel(model, lianmai: true)
              
            } else {
                self.keynoteLive.videoArea.update1to1Model(model)
               
            }
        } else if (self.talkfunSDK.pageMode == TalkfunPageModeGallery){
            self.galleryLive.videoArea.updateModel(model)
            
        }

        let chatData = TF1to16LiveChatData()
        chatData.nickname = model.nickname
        chatData.score = model.score
        chatData.isAward = true
        //奖励
        self.chatArea.setAwardModel(chatData)
        if (model.isMe) {
            self.superView.addSubview(self.awardView)
            self.awardView.rotateView()
        }
    }

   // #pragma mark ---------- 房间事件回调
    func onEnterRoom(_ code: Int, result error: TFError) {
        
        
        //TODO: 设置
        if (self.setButtonView.frame.width==0) {
            self.setButtonView.initUI(frame: CGRect(x: self.superView.frame.size.width+220, y: 0, width: self.superView.frame.size.width, height: self.superView.frame.size.height), xid: self.talkfunSDK.xid)
           

        self.setButtonView.xid = self.talkfunSDK.xid
        self.setButtonView.delegate2 = self
        self.setButtonView.contentSize = CGSize(width: 0, height: 400)
 
        self.superView.addSubview(self.setButtonView)

        }
        //初始化成功
        if (code == 0 ) {
            self.barrageRender.bulletSwitch = TalkfunSettingToolsManager.shared().getToolsSwitchBarrage(self.talkfunSDK.xid)
            
            self.zhuboName = self.talkfunSDK.roomInfo.zhuboInfo.nickname
            if (self.isRefresh) {
            if (self.talkfunSDK.pageMode == TalkfunPageModeCourse) {
                self.addCourseMode()

            } else if (self.talkfunSDK.pageMode == TalkfunPageModeKeyNote) {
                self.addkeynoteMode()

                self.keynoteLive.keynoteView.nameLab.text = self.zhuboName

            } else if (self.talkfunSDK.pageMode == TalkfunPageModeGallery) {
                self.addgalleryMode()

            }
            }
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1.0) {
          
                self.isShow = true
                   }
    
   
            
            let isOn = TalkfunSettingToolsManager.shared().getToolsLanguageChange(self.talkfunSDK.xid)
          
             if (isOn) {
                 TFChangeLanguage.sharedInstance.setLanguage(language: "en")
                 self.updataLanguage(isOn)
               
             }

            //课前聊天
            self.mod_beforeclass_live = self.talkfunSDK.roomInfo.mod_beforeclass_live.config.chat.enable
            //课后聊天
            self.mod_afterclass_live = self.talkfunSDK.roomInfo.mod_afterclass_live.config.chat.enable
            //设置聊天
            self.navigationBar.showChat = self.talkfunSDK.roomInfo.mod_text_live.config.chat.enable
            //设置问答
            self.navigationBar.showQa = self.talkfunSDK.roomInfo.mod_text_live.config.qa.enable
            //设置投票
            self.navigationBar.showVote = self.talkfunSDK.roomInfo.mod_zhuboaction_live.config.vote.enable

            self.navigationBar.title.text = self.talkfunSDK.roomInfo.title
            if (self.talkfunSDK.roomInfo.mod_liveinfo_live.config.title.enable == true) {
                self.navigationBar.title.isHidden = false
            } else {
                self.navigationBar.title.isHidden = true
            }

            if (self.talkfunSDK.roomInfo.zhujiang.enable == false) {
            self.zhujiangStatus = 0
            }else{
            self.zhujiangStatus = self.talkfunSDK.roomInfo.zhujiang.status
            self.zhujiangxid = self.talkfunSDK.roomInfo.zhujiang.xid
            }

            self.userNickname = self.talkfunSDK.roomInfo.myInfo.nickname
            self.promptTool.loading.isHidden = true
            self.votingArea.voteDetail.uid = self.talkfunSDK.uid
            self.chatArea.uid = self.talkfunSDK.uid
            ///  只有显示的时候才请求课件数据  课件下载开头
            if (self.talkfunSDK.roomInfo.mod_document_download_live.enable) {
                self.navigationBar.showCourseDown = true

            } else {
                self.navigationBar.showCourseDown = false
            }

        }
    }
    
    func getMediaAreawidth()->CGFloat
    {
        var  mediaAreawidth:CGFloat = 0
        if (UIDevice.current.userInterfaceIdiom == .phone)
           {
               mediaAreawidth = 158
           }else{
               mediaAreawidth = 184

           }
        return mediaAreawidth
    }
    deinit {
            print("成功退出小班1v1界面")
        }
}
